import jwt from 'jwt-simple'
import { TOKEN_KEY } from '#config'
import { AuthError } from './error.js'

export default {
  // 获取服务端cookie
  getToken: (req) => {
    return req && req.headers['cute-token']
  },
  // 检查token
  check(token) {
    if (!token) throw new AuthError()
    //解密获取的token
    let decoded = jwt.decode(token, TOKEN_KEY)
    //校验有效期
    if (!decoded || !decoded.exp || decoded.exp <= Date.now()) throw new AuthError('登录状态已过期')
    return decoded
  },
  // 创建token
  create(obj) {
    return jwt.encode(obj, TOKEN_KEY)
  },
}
